import React, {PropsWithChildren, useEffect, useMemo, useState} from 'react'
import {Cascader} from "antd";
import {AdministrativeRegionTreeResponse, getAdministrativeRegionTree} from "../apis/AdministrativeRegionApi";

export interface AdministrativeRegionCascaderProps extends PropsWithChildren {
    value?: string
    onChange?: (value: string) => void
}

const AdministrativeRegionCascader: React.FC<AdministrativeRegionCascaderProps> = (props) => {
    const [data, setData] = useState<AdministrativeRegionTreeResponse[]>([])
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        setLoading(true)
        getAdministrativeRegionTree().then(response => {
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, []);

    // 1. 根据单个 code 值查找完整的路径数组
    const cascaderValue = useMemo(() => {

        let value = props.value;
        const array:string[] = []

        let province = data.find(it=>it.code===value?.substring(0,2) + "0000");
        if (province){
            array.push(province.code)
            let second = province.children.find(it=>it.code===value?.substring(0,4) + "00");
            if (second){
                array.push(second.code)
            }
            if (value!==province.code){
                array.push(value!!)
            }
        }

        return array.length?array:undefined
    }, [props.value, data]);
    return <>
        <Cascader allowClear showSearch loading={loading} options={data}
                  value={cascaderValue}
                  fieldNames={{value: "code", label: "name", children: 'children'}} onChange={(v) => {
            props.onChange?.(v[v.length - 1])
        }}/>
    </>
}

export default AdministrativeRegionCascader


